<?php

class Messages extends MY_Controller {
    
    function __construct() {
        parent::__construct();
    }
    
    public function send() {
        $this->load->library('user_agent');
        $title = $this->input->post('message_title');
        $content = $this->input->post('message_content');
        $to_user_id = $this->input->post('to_user');
        $message = new Message();
        $user = new User();
        
        $user->where('id', $to_user_id)->get();
        $message->author_id = $this->session->userdata('user_id');
        $message->title = $title;
        $message->content = $content;
        if ($message->save($user)) {
            $this->session->set_flashdata('flashMessage', 'Private message successfully sent!');
            $this->session->set_flashdata('flashMessageType', 'success');
        } else {
            $this->session->set_flashdata('flashMessage', 'Private message was not sent. Try again or contact admin');
            $this->session->set_flashdata('flashMessageType', 'danger');
        }
         redirect($this->agent->referrer());
    }
    
    public function myMessages() {
        $message = new Message();
        $user = new User();
        
        /*$message->where_related('user', 'id', $this->session->userdata('user_id'))
                ->get()->all;*/
        $sql = "SELECT `messages`.*, `users`.username as sender_username
                FROM (`messages`)
                LEFT OUTER JOIN `messages_users` messages_users ON
                        `messages`.`id` = `messages_users`.`message_id`
                LEFT OUTER JOIN `users` users ON `users`.`id` =
                        `messages`.`sender_id`
                WHERE `messages_users`.`user_id` =  '1'";
        $message->query($sql);
        $total = $message->result_count();
        $unread = $message->where('is_read', 0)->count();
        
        $data['total'] = $total;
        $data['messages'] = $message;
        $data['template'] = 'user_area/messages_list';
        $this->load->view('template', $data);
    }
    
    public function read($id = NULL) {
        $message = new Message();
        $user = new User();
        
        $message->where('id', $id)->get();
        if ($message->is_read == 0) {
            $message->update('is_read', 1);  
        }
        $user->where('id', $message->author_id)->get();
        
        $data['message'] = $message;
        $data['sender'] = $user;
        $data['template'] = 'user_area/message_single';
        $this->load->view('template', $data); 
    }
}

/* End of file messages.php */
/* Location: ./application/controllers/messages.php */